package io;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

/**
 * @author krystal
 * @date 2022/11/27 10:16
 */
public class Demo12 {
    public static void main(String[] args) throws IOException {
        //1.让用户输入了必要的信息
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入要扫描的路径：");
        File rootDir=new File(scanner.next());
        if (!rootDir.isDirectory()){
            System.out.println("您输入的目录不存在！");
            return;
        }
        System.out.println("请输入要搜索的关键词：");
        String toDelete=scanner.next();

        //2.遍历目录
        scanDir(rootDir,toDelete);


    }

    private static void scanDir(File rootDir,String toDelete) throws IOException {
        System.out.println("当前访问"+rootDir.getCanonicalPath());
        File[] files=rootDir.listFiles();
        if(files==null){
            //说明rootDir是一个空的目录
            return;
        }
        //如果目录非空，循环遍历每个元素
        for (File f:files){
            if (f.isDirectory()){
                scanDir(f,toDelete);
            }else {
                //不是目录，是普通文件，判定文件名是否符合要求，是否要进行删除
                checkDelete(f,toDelete);
            }
        }
    }

    private static void checkDelete(File f, String toDelete) throws IOException {
        if (f.getName().contains(toDelete)){
            System.out.println("该单词"+toDelete+"被"+f.getCanonicalPath()+"包含了，是否删除？(Y/N)");
            Scanner scanner=new Scanner(System.in);
            String choice=scanner.next();
            if (choice.equals("Y")||choice.equals("y")){
                f.delete();
            }
        }
    }
}
